package app.fugema.shop.main.home.view;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;
import app.fugema.shop.constants.PublicGlobal;
import app.fugema.shop.main.home.vm.MyCenterVM;
import app.fugema.shop.main.login.view.LoginActivity;

import android.app.Activity;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.base.common.app.AppManager;
import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.LogUtil;
import com.base.common.utils.NoticeUtils;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.SPUtils;
import com.base.common.view.base.BaseActivity;
import com.base.common.view.base.BaseFragment;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.map.tools.json.JsonUtils;
import com.umeng.commonsdk.utils.UMUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityMainBinding;
import app.fugema.shop.main.order.view.ShoppingCartActivity;

public class MainActivity extends BaseActivity<ActivityMainBinding, MyCenterVM> {

    public static void lunch(Context context)
    {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private enum Item {
        home("首页", new HomePageFragment()),
        live("分类", new HomeClassifyFragment()),
        note("店铺", new HomeStoreFragment()),
        cart("购物车", new HomeClassifyFragment()),
        myCenter("个人中心", new HomeMyCenterFragment());

        public String name;
        public BaseFragment fragment;

        Item(String name, BaseFragment fragment) {
            fragment.setTitle(name);
            this.name = name;
            this.fragment = fragment;
        }

    }

    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(AppConstants.EventKey.GO_TO_HOME_PAGE, Integer.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                AppManager.getInstance().closeTopActivity(MainActivity.this.getClass());
                if (integer != null && integer > -1 && integer < Item.values().length) {
                    if (binding.vpPager != null) {
                        binding.vpPager.setCurrentItem(integer, false);
                    }
                }
            }
        });

        //跳转到登录
        LiveEventBus.get(BaseConstant.LOGIN_IN).observe(this, new Observer<Object>() {
            @Override
            public void onChanged(Object o) {
                LoginActivity.lunch(getActivity());
            }
        });

        //初始化 友盟推送
        //initUPush();
        //切换登录 后 重新设置别名
        LiveEventBus.get("StartUPush",Integer.class).observeSticky(this, result ->{
            initUPush();
        });

    }

    @Override
    protected void initView() {
        super.initView();

        SPUtils.putBoolean(AppConstants.GUIDE_LOGIN, false);

        //如果是从点击通知栏的通知跳转过来的
        NoticeUtils.isAppWithNoticeOpen(this);

        binding.vpPager.setScroll(false);

        binding.vpPager.setOffscreenPageLimit(5);

        binding.vpPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position)
            {
                return Item.values()[position].fragment;
            }

            @Override
            public int getCount()
            {
                return Item.values().length;
            }
        });


        binding.vpPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                stop(binding.lavHomePage);
//                stop(binding.lavHomeLive);
//                stop(binding.lavMsg);
//                stop(binding.lavMyCenter);
                binding.llHomePage.setSelected(false);
                binding.llHomeLive.setSelected(false);
                binding.llMsg.setSelected(false);
                binding.llcart.setSelected(false);
                binding.llMyCenter.setSelected(false);

                switch (position) {
                    case 0:
//                            start(binding.lavHomePage);
                        binding.llHomePage.setSelected(true);
                        break;
                    case 1:
//                            start(binding.lavHomeLive);
                        binding.llHomeLive.setSelected(true);
                        break;
                    case 2:
//                            start(binding.lavMsg);
                        binding.llMsg.setSelected(true);
                        break;
                    case 3:
//                            start(binding.lavMyCenter);
                        binding.llcart.setSelected(true);
                        break;
                    case 4:
//                            start(binding.lavMyCenter);
                        binding.llMyCenter.setSelected(true);
                        break;
                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        binding.llHomePage.setSelected(true);
        viewUtils.setStateLayout(binding.vpPager, this);


        binding.llHomePage.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                binding.vpPager.setCurrentItem(0, false);
            }
        });
        binding.llHomeLive.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                binding.vpPager.setCurrentItem(1, false);
                //商品分类
                //GoodsClassifyActivity.start(view.getContext());
            }
        });
        binding.llMsg.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                binding.vpPager.setCurrentItem(2, false);
            }
        });
        binding.llcart.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                //binding.vpPager.setCurrentItem(3, false);

                ShoppingCartActivity.start(view.getContext());
            }
        });
        binding.llMyCenter.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                binding.vpPager.setCurrentItem(4, false);
            }
        });

        binding.llHomePage.setSelected(true);
    }


    private void stop(LottieAnimationView view)
    {
        if (view == null) return;
        if (view.isAnimating()) {
            view.pauseAnimation();
        }
        view.setFrame(0);
    }

    private void start(LottieAnimationView view) {
        if (view == null) return;
        view.playAnimation();
    }

    @Override
    public void onBackPressed() {

        if (viewUtils.onBackPressed())
        {
            AppManager.getInstance().removeAllActivity();
        }
    }

    public boolean isCanAlias = false;
    //友盟推送
    public void initUPush()
    {

        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //sdk开启通知声音
        //mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        //服务端控制声音
        //mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);
        UmengMessageHandler messageHandler = new UmengMessageHandler() {

            /**
             * 通知的回调方法（通知送达时会回调）
             */
            @Override
            public void dealWithNotificationMessage(Context context, UMessage msg) {
                //调用super，会展示通知，不调用super，则不展示通知。
                super.dealWithNotificationMessage(context, msg);
            }

            /**
             * 自定义消息的回调方法
             */
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg)
            {
                LogUtil.e("mainHome" , msg.custom +" --> " +JacksonUtils.transBean2Json( msg ));
            }
            /**
             * 自定义通知栏样式的回调方法
             */
            @Override
            public Notification getNotification(Context context, UMessage msg)
            {
                return super.getNotification(context, msg);
            }
        };
        mPushAgent.setMessageHandler( messageHandler);

/**
 * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
 * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
 * */
        //通知点击事件
        UmengNotificationClickHandler notifiClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void dealWithCustomAction(Context context, UMessage msg)
            {
                if(UMUtils.isMainProgress(context))
                {
                    Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                }
                else
                {
                    LogUtil.e("UPush",msg.custom);

                    //{"display_type":"notification","extra":{"ExtraData":""},"body":{"after_open":"go_app","img":"","ticker":"福格码","activity":"","custom":"","sound":"","icon":"","title":"canxi您的商品已发送","play_sound":"true","url":"","play_vibrate":"true","largeIcon":"","text":"canxi您在官方自营8号店-1购买的多伦保罗拉杆箱万向轮登机箱学生旅行箱制定子母箱男女化妆箱已经发货,物流单号:1231231231231231"},"msg_id":"uulv1a1162752113047800"}
                    //{"display_type":"notification","extra":{"ExtraData":{"Type":"","typeInfo":"2","Content":"","Phone":"","Title":"","typeId":"2021071371973585"}},"body":{"after_open":"go_app","img":"","ticker":"福格码","activity":"","custom":"","sound":"","icon":"","title":"海纳通1您的商品已发送","play_sound":"true","url":"","play_vibrate":"true","largeIcon":"","text":"海纳通1您在官方自营9号店-1购买的正品牌瑞之缘手表男士全自动机械表钢带镂空时尚腕表（工厂直销  终身保修）已经发货,物流单号:SF1323585071125"},"msg_id":"uu2zbg4162752364875300"}

                }

                int typeId = Integer.parseInt( msg.extra.get("typeInfo") );
                LogUtil.e("typeInfo",""+typeId);

            }
        };
        mPushAgent.setNotificationClickHandler(notifiClickHandler);

        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new UMRegisterCallBack(MainActivity.this));


        /**
         * 初始化厂商通道
         */
        //小米通道
        //MiPushRegistar.register(this, PushConstants.MI_ID, PushConstants.MI_KEY);
        //华为通道，注意华为通道的初始化参数在minifest中配置
        //HuaWeiRegister.register(this);
        //魅族通道
        //MeizuRegister.register(this, "填写您在魅族后台APP对应的app id", "填写您在魅族后台APP对应的app key");
        //OPPO通道
        //OppoRegister.register(this, "填写您在OPPO后台APP对应的app key", "填写您在魅族后台APP对应的app secret");
        //VIVO 通道，注意VIVO通道的初始化参数在minifest中配置
        //VivoRegister.register(this);
    }


    class UMRegisterCallBack implements IUmengRegisterCallback
    {
        private Activity mAty;

        public UMRegisterCallBack(Activity mAty) {
            this.mAty = mAty;
        }

        @Override
        public void onSuccess(String deviceToken)
        {
            isCanAlias = true;
            //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
            LogUtil.e("Home","注册成功：deviceToken：-------->  " + deviceToken);
            PublicGlobal.setDeviceToken(deviceToken);
            //只有 注册成功 获取到 deviceToken 才能设置别名
            if(LoginUtils.isLogin())
            {
                PushAgent.getInstance(this.mAty).setAlias(String.valueOf( LoginUtils.getUserId() ), "uid", new UTrack.ICallBack()
                {
                    @Override
                    public void onMessage(boolean b, String s)
                    {
                        isCanAlias = false;
                        runOnUiThread(()-> {
                            //提交设置别名 deviceToken
                            viewModel.setUesrDeviceToken(LoginUtils.getUserId(),deviceToken)
                                    .observe(MainActivity.this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>() {
                                        @Override
                                        protected void onSuccess(LiveDataWrapper<BaseApiResult> data) {

                                        }
                                    });
                                }
                        );

                        LogUtil.e("Home"," Alias result = " + s);
                    }
                });
            }
        }

        @Override
        public void onFailure(String s, String s1)
        {
            Log.e("Home","注册失败：-------->  " + "s:" + s + ",s1:" + s1);
        }
    }

}